package springboot.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import springboot.doMain.Msg;
import springboot.doMain.PostTest;
import springboot.doMain.WxGroup;
import springboot.http.WXWorkApi;
import springboot.service.impl.MsgServiceImpl;
import springboot.service.impl.WXGroupServiceImpl;

import java.util.List;
import java.util.Map;

@Controller
public class exApi {
	
	
	final
	WXGroupServiceImpl wxGroupService;
	
	@Autowired
	MsgServiceImpl msgService;
	
	
	public exApi(WXGroupServiceImpl wxGroupService) {
		this.wxGroupService = wxGroupService;
	}
	
	
	@GetMapping("/sun")
	@ResponseBody
	public String insertGroupName() {
		new Thread(this::insertNoCpName).start();
		
		return "ok";
	}
	
	@GetMapping("/postTest")
	@ResponseBody
	public PostTest postTest(PostTest postTest) {
		
		return postTest;
	}
	
	public void insertNoCpName() {
		msgService.updateAllMsgAndWorkMsg();
		String token = WXWorkApi.getToken();
		List<Map<Object, Object>> notInsertWxGroup = msgService.getNotInsertWxGroup();
		
		notInsertWxGroup.forEach(objectObjectMap -> {
			Msg msg = new Msg();
			msg.setCpId(objectObjectMap.get("chat_id") + "");
			String groupInfo = WXWorkApi.getGroupInfo(msg.getCpId(), token);
			WxGroup instance = WxGroup.getInstance(groupInfo);
			if (instance != null) {
				wxGroupService.insert(instance);
				msg.setCpName(instance.getName());
				msg.setCpId(instance.getChatId());
				msgService.updateGroupName(msg);
				msgService.updateAllMsgGroupName(msg);
			} else {
				WxGroup wxGroup = new WxGroup();
				wxGroup.setChatId(msg.getCpId());
				
				WxGroup wxGroupByChatId = wxGroupService.selWxGroupByChatId(wxGroup);
				Msg msg1 = new Msg();
				if (wxGroupByChatId != null) {
					msg1.setCpId(wxGroupByChatId.getChatId());
					msg1.setCpName(wxGroupByChatId.getName());
					msgService.updateGroupName(msg1);
					msgService.updateAllMsgGroupName(msg1);
				}
			}
		});
	}
	
	
}
